#!/usr/bin/env python
# -*- coding: utf-8 -*-

from typing import List, Dict, Any, Optional

from fastapi import APIRouter, Depends, HTTPException, Path
from fastapi.responses import PlainTextResponse

from app.core.dependencies import get_services
from app.core.exceptions import NotFoundError, SQLGenerationError
from app.models.api import Text2SQLRequest, Text2SQLResponse

# 创建路由
router = APIRouter()


@router.post("/{project_id}/text2sql", response_class=PlainTextResponse)
async def generate_sql(
    request: Text2SQLRequest,
    project_id: str = Path(..., description="项目ID"),
    services=Depends(get_services)
):
    """生成SQL查询
    
    根据自然语言问题生成SQL查询
    """
    try:
        # 检查项目是否存在
        await services["project_service"].get_project(project_id)
        
        # 生成SQL
        sql = await services["text2sql_service"].generate_sql(
            project_id=project_id,
            question=request.question,
            db_type=request.db_type,
            system_prompt=request.system_prompt
        )
        
        # 直接返回SQL文本
        return sql
    except NotFoundError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except SQLGenerationError as e:
        raise HTTPException(status_code=500, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"生成SQL失败: {str(e)}")